# -*- coding: utf8 -*-
#!/usr/bin/python
import json
import os
import sys
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.escape
from tornado.options import define, options
from handler import *
from TeacherHelper import *


class MainHandler(APIHandler):
    def get(self):
        pass
    def post(self):
        pass

class DownloadHandler(APISecureHandler):

    @tornado.web.authenticated
    def get(self):
        stu = Student.instance()
        stu.logger.info('download....')
        stu.logger.info(self.get_argument('id'))
        self.set_header('Content-Type','application/msexcel')
        self.set_header('Content-Disposition','attachment;filename="abc.xls"')
        #len =str(os.path.getsize('/opt/simp/static/downloads/attendinfo.xls'))
        #self.set_header('Content-Length',len)
        #with open('/opt/simp/static/downloads/attendinfo.xls','rb') as f:
        self.write({'path':'/static/downloads/attendinfo.xls'})

class LoginHandler(APIHandler):
    def get(self):
        loginUrl = self.get_argument('login_url')
        user = self.get_argument('user')
        pwd = self.get_argument('pwd')
        tHelper = TeacherHelper.instance()
        tHelper.init(loginUrl,user,pwd)
        ret = tHelper.login()
        if ret :
            #登录的用户名和密码，比对数据库，如果有更新，如果没有，新增
            self.finish(notification="登录成功")
        else:
            self.finish(success=False,notification="登录失败")
            #self.write_error(500,'登录失败')

class UploadFileHandler(BaseHandler):
    def get(self):
        self.render('upload.html')

        pass
    def post(self):
        #add user param to the post url
        user = self.get_argument('user')
        week = self.get_argument('week')
        fname = self.get_argument('fname')
        print user,"..........."
        uploadPath = os.path.join(os.path.dirname(__file__),'files/new',user,week)
        if not os.path.exists(uploadPath):
            print 'create a dict...'
            os.makedirs(uploadPath)
        #data = self.request.body

        filePath = os.path.join(uploadPath,fname)
        print '----file path----',filePath
        #with open(filePath,'wb') as up:
        #    up.write(data)
        fileMetas = self.request.files['file']
        count = len(fileMetas)
        for meta in fileMetas:
            #fileName = os.path.basename(meta['filename'])
            #filePath = os.path.join(uploadPath,fileName)
            with open(filePath,'wb') as up:
                up.write(meta['body'])

        self.finish()

#上传到教案系统文件会move to /files/old/username/
class UploadStatusHandler(APIHandler):
    def get(self):
        user = self.get_argument('user')
        pwd = self.get_argument('pwd')
        loginUrl = self.get_argument('login_url')
        #get all file that already uploaded
        tHelper = TeacherHelper.instance()
        tHelper.init(loginUrl,user,pwd)
        uploadFiles = tHelper.getFileList()
        count = len(uploadFiles)



        #get files which is not be uploaded
        uploadPath = os.path.join(os.path.dirname(__file__),'files/new',user)
        uploadPath = os.path.abspath(uploadPath)
        print uploadPath
        unUploadFiles = os.listdir(uploadPath)

        #self.finish(key='uploaded',total=count,chunk=uploadFiles)
        self.finish(key='files',chunk={'unUploadFiles':unUploadFiles,'uploadFiles':uploadFiles})

    def post(self):
        pass

class DeleteFilesHandlers(APIHandler):
    def get(self):
        pass
    def post(self):
        user = self.get_argument('user')
        pwd = self.get_argument('pwd')
        loginUrl = self.get_argument('login_url')
        #files={'ids':[123,3456,786],'names':['xxxx.doc','xyz.doc']}
        files = self.get_argument('files')
        files = json.loads(files)

        #delete files that already uploaded
        tHelper = TeacherHelper.instance()
        tHelper.init(loginUrl,user,pwd)
        try:
            for fid in files['ids']:
                tHelper.deleteFile(fid)
        except Exception as e :
            print e
        #delete files that is not be uploaded
        uploadPath = os.path.join(os.path.dirname(__file__),'files/new',user)
        uploadPath = os.path.abspath(uploadPath)
        for fname in files['names']:
            filePath = os.path.join(uploadPath,fname)
            if os.path.exists(filePath) and os.path.isfile(filePath):
                os.remove(filePath)

        self.finish()


if __name__ == "__main__":
    #reload(sys)
    #sys.setdefaultencoding('utf-8')
    settings = {
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        "cookie_secret":"74deccaf0bfc574e7487f931b9c07d16=+-_",
        'login_url':'/login'
        }

    application = tornado.web.Application([
        (r"/",MainHandler,),
        (r"/login",LoginHandler,),
        (r"/upload",UploadFileHandler,),
        (r"/status",UploadStatusHandler)
        ],
        **settings
        )
    application.listen(8090)
    tornado.ioloop.IOLoop.instance().start()
